package com.sunny.core.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunny.core.bean.PersonInfo;
import com.sunny.core.bean.PolicyInfo;
import com.sunny.core.bean.PolicyMaster;
import com.sunny.core.bean.PolicyMaster;
import com.sunny.core.bean.UserInfo;
import com.sunny.core.service.IPolicyInfoService;
import com.sunny.core.service.IPolicyMasterService;
import com.sunny.core.service.IPolicyMasterService;
import com.sunny.core.utils.CommonResult;
import com.sunny.core.utils.CommonStringUtils;
import com.sunny.core.utils.Constant;

@Controller
@RequestMapping("/policyMaster")
public class PolicyMasterController {

	@Resource(name = "policyMasterService")
	private IPolicyMasterService policyMasterService;

	@Resource(name = "policyInfoService")
	private IPolicyInfoService policyInfoService;
	
	/**
	 * 保单查询
	 */
	@RequestMapping(value = "/query", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView queryAll(HttpServletRequest request,
			HttpServletResponse response, Model m) throws Exception {

		PolicyMaster policyMaster = new PolicyMaster();

		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");

		int num = 1;
		int size = 10;
		if (pageNum != null && !"".equals(pageNum)) {
			num = Integer.parseInt(pageNum);
		}
		if (pageSize != null && !"".equals(pageSize)) {
			size = Integer.parseInt(pageSize);
		}
		String sortString = "id.desc";
		Order.formString(sortString);

		PageHelper.startPage(num, size);

		String searchType = request.getParameter("searchType");
		String searchValue = request.getParameter("searchValue");

		 if (StringUtils.isNotBlank(searchType)) {
		 if (searchType.equals("policyCode")) {
			 policyMaster.setPolicyCode(searchValue);
		 }
//		 if (searchType.equals("2")) {
//			 policyMaster.setBirthday(searchValue);
//		 }
		 }

		List<PolicyMaster> policyMasterList = policyMasterService.query(policyMaster);

		PageInfo<PolicyMaster> pagehelper = new PageInfo<PolicyMaster>(
				policyMasterList);

		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// 相当 于request的setAttribut，在jsp页面中通过personList取数据
		// modelAndView.addObject("personList", personList);
		modelAndView.addObject("pagehelper", pagehelper);

		m.addAttribute("policyMasterList", policyMasterList);
		m.addAttribute("total", pagehelper.getTotal());
		m.addAttribute("pageSize", pagehelper.getPageSize());
		m.addAttribute("pageNum", num);
		m.addAttribute("searchType", searchType);
		m.addAttribute("searchValue", searchValue);

		// 指定视图
		// 下边的路径，如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀，修改为
		// modelAndView.setViewName("/jsp/personList.jsp");
		// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
		modelAndView.setViewName("policy/policy_master_list");
		return modelAndView;

	}

	
	@RequestMapping(value = "/delete", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public CommonResult delete(HttpServletRequest request,HttpSession session,PolicyMaster policyMaster) throws Exception {	
		CommonResult commonResult = new CommonResult();
		String policyMasterPid = request.getParameter("policyMasterPid");
		policyMaster.setPolicyMasterPid(policyMasterPid);
		policyMaster.setDelFlag(1);
		
		PolicyMaster entity = policyMasterService.selectByPolicyMasterPid(policyMaster);
		
		int result = policyMasterService.updateByPrimaryKeySelective(policyMaster);
		
		List<PolicyInfo> policyInfoList = entity.getPolicyInfoList();
		PolicyInfo policyInfo = null;
		for (int i=0;i<policyInfoList.size();i++){
			policyInfo = policyInfoList.get(i);
			policyInfo.setDelFlag(1);
			policyInfoService.updateByPrimaryKeySelective(policyInfo);
		}
		
		if (result == 1) {
			commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
			commonResult.setMsg(Constant.RESULT_DELSUC_DESC);
		} else {
			commonResult.setStatus(Constant.RESULT_ERROR_CODE);
			commonResult.setMsg(Constant.RESULT_DELERR_DESC);
		}
		return commonResult;
	}
	
	/**
	 *  跳到保单详情页面
	 */
	@RequestMapping(value = "/toDetail", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView toDetail(HttpServletRequest request,
			HttpServletResponse response,Model m,PolicyMaster policyMaster) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		
		if (policyMaster != null && StringUtils.isNotBlank(policyMaster.getPolicyMasterPid())) {
			PolicyMaster entity = policyMasterService.selectByPolicyMasterPid(policyMaster);
			
			if (entity != null) {
				
				m.addAttribute("flag","detail");
				m.addAttribute("policyMaster",entity);
				m.addAttribute("policyInfoList",entity.getPolicyInfoList());
				
				modelAndView.setViewName("policy/policy_master_crud");
				return modelAndView;
			}
		}
		return null;
	}
	
	/**
	 *  跳到险种编辑页面
	 */
	@RequestMapping(value = "/toEdit", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView toEdit(HttpServletRequest request,
			HttpServletResponse response,HttpSession session,Model m,PolicyMaster policyMaster) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		
		if (policyMaster != null && StringUtils.isNotBlank(policyMaster.getPolicyMasterPid())) {
			
			PolicyMaster policyMasterFromDB = policyMasterService.selectByPolicyMasterPid(policyMaster);
			

			if (policyMasterFromDB != null) {
				m.addAttribute("flag","edit");
				m.addAttribute("policyMaster",policyMasterFromDB);
				m.addAttribute("policyInfoList",policyMasterFromDB.getPolicyInfoList());
				modelAndView.setViewName("policy/policy_master_crud");
				
			}
			return modelAndView;
			
		}
		return null;
	}	
	
	/**
	 *  跳到人员新增页面
	 */
	@RequestMapping(value = "/toAdd", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView toAdd(HttpServletRequest request,
			HttpServletResponse response,HttpSession session,Model m) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		String flag = request.getParameter("flag");
		// 相当 于request的setAttribut，在jsp页面中通过personList取数据
		// modelAndView.addObject("personList", personList);
		if ("loadSession".equals(flag)){//加载session
			PolicyMaster entity = (PolicyMaster)session.getAttribute("policyMaster");
			@SuppressWarnings("unchecked")
			List<PolicyInfo> policyInfoList = (List<PolicyInfo>)session.getAttribute("policyInfoList");
			m.addAttribute("policyMaster",entity);
			m.addAttribute("policyInfoList",policyInfoList);
		} else {
			session.setAttribute("policyMaster", null);
			session.setAttribute("policyInfoList", null);
			m.addAttribute("policyMaster",new PolicyMaster());
			m.addAttribute("policyInfoList",new ArrayList<PolicyInfo>());
		}
		
		// 指定视图
		// 下边的路径，如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀，修改为
		// modelAndView.setViewName("/jsp/personList.jsp");
		// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
		modelAndView.setViewName("policy/policy_master_crud");
		return modelAndView;

	}	

	
	@RequestMapping(value = "/add", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public CommonResult add(HttpServletRequest request,HttpSession session,PolicyMaster policyMaster) throws Exception {	
		CommonResult commonResult = new CommonResult();
		commonResult.setStatus(Constant.RESULT_ERROR_CODE);
		commonResult.setMsg(Constant.RESULT_ADDERR_DESC);
		
		UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");
		
		@SuppressWarnings("unchecked")
		List<PolicyInfo> policyInfoList = (List<PolicyInfo>)session.getAttribute("policyInfoList");
		
		if (policyMaster == null){
			return commonResult;
		}
		
		policyMaster.setPolicyMasterPid(CommonStringUtils.get32UUID());
		policyMaster.setDelFlag(0);
		policyMaster.setCreateTime(new Date());
		policyMaster.setCreateUserid(currentUser.getUserPid());
		policyMaster.setCreateUsername(currentUser.getRealName());
		
		if (CollectionUtils.isEmpty(policyInfoList)) {
			policyInfoList = new ArrayList<PolicyInfo>();
		}
		
		PolicyInfo policyInfo = null;
//		BigDecimal premium = new BigDecimal(0);//累积应缴保费
		
		for(int i=0;i<policyInfoList.size();i++){
			
			policyInfo = policyInfoList.get(i);

			policyInfo.setPolicyCode(policyMaster.getPolicyCode());
			policyInfo.setDelFlag(0);
			policyInfo.setCreateTime(new Date());
			policyInfo.setCreateUserid(currentUser.getUserPid());
			policyInfo.setCreateUsername(currentUser.getRealName());
			
//			premium = premium.add(policyInfo.getPremiumPayable());//应缴保费相加
			
			if ("附加".equals(policyInfo.getInsuranceName())){
				policyInfo.setMainFlag(0);
			} else {
				policyInfo.setMainFlag(1);
				policyMaster.setInsuranceName(policyInfo.getInsuranceName());//险种名称
			}
			
			policyInfoService.save(policyInfo);
		}
		
//		policyMaster.setPremiumPayable(premium);//set 总应缴保费
		int result = policyMasterService.save(policyMaster);
		
		if (result == 1) {
			commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
			commonResult.setMsg(Constant.RESULT_ADDSUC_DESC);
		}
		return commonResult;
	}
	

	@RequestMapping(value = "/update", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public CommonResult update(HttpServletRequest request,HttpSession session,PolicyMaster policyMaster) throws Exception {	
		CommonResult commonResult = new CommonResult();
		
		commonResult.setStatus(Constant.RESULT_ERROR_CODE);
		commonResult.setMsg(Constant.RESULT_UPERR_DESC);
		
		if (policyMaster != null && policyMaster.getPolicyMasterPid() != null) {
			
			UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");
			policyMaster.setUpdateTime(new Date());
			policyMaster.setUpdateUserid(currentUser.getUserPid());
			policyMaster.setUpdateUsername(currentUser.getRealName());
			
			int result = policyMasterService.updateByPrimaryKeySelective(policyMaster);
			
			if (result == 1) {
				commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
				commonResult.setMsg(Constant.RESULT_UPSUC_DESC);
				commonResult.setData(policyMaster.getPolicyMasterPid());
				
			}
		}

		return commonResult;
	}	
	
}
